package cn.springcloud.fix.stomp.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

@Slf4j
public class FileUtil {

    public static boolean downloadToDir(String url, String dir) {
        try {
            if (StringUtils.isBlank(url)) {
                return false;
            } else {
                String fileName = CommonUtil.getNameFromUrl(url);
                String dowPath = dir + "/" + fileName;
                return download(url, dowPath);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public static boolean download(String dowUrl, String dowPath) {
        try {
            if (StringUtils.isBlank(dowUrl)) {
                return false;
            }
            log.info("下载地址是：" + dowUrl + ",存储地址是：" + dowPath);
            URL url = new URL(dowUrl);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            httpURLConnection.setConnectTimeout(20000);
            httpURLConnection.connect();
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            OutputStream out = new FileOutputStream(dowPath);
            byte[] b = new byte[2048];

            int size;
            while ((size = bin.read(b)) != -1) {
                out.write(b, 0, size);
            }

            bin.close();
            out.close();
            return true;
        } catch (Exception var9) {
            log.error(var9.getMessage(), var9);
            return false;
        }
    }
}
